package cn.edu.ctbu.lab.api;

import cn.edu.ctbu.lab.domain.Course;
import cn.edu.ctbu.lab.helper.RUtil;
import cn.edu.ctbu.lab.service.CourseService;
import cn.edu.ctbu.lab.vo.BTPageDO;
import cn.edu.ctbu.lab.vo.CourseExt;
import cn.edu.ctbu.lab.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.data.domain.Page;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.sql.Date;
import java.text.SimpleDateFormat;

@Slf4j
@RestController
public class CourseRestController {
    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    @Autowired
    private CourseService courseService;

    /**
     * 基本分页
     * @param
     * @return
     */
    @GetMapping(value = "/api/course/read")
    public  R read(Integer id){
        Course course = courseService.findById(id).get();

        return  RUtil.success(course);

    }

    @PostMapping(value = "/api/course/add")
    public R add(@Valid Course course, BindingResult bindingResult){

        if(bindingResult.hasErrors()){
            log.info(bindingResult.getFieldError().getDefaultMessage());
            return RUtil.error(-2,
                    "出错了!"+bindingResult.getFieldError().getDefaultMessage());
        }
        courseService.add(course);

        return RUtil.success();

    }

    @PutMapping(value = "/api/course/update") //valid看Info 是否满足需要
    public R update(@Valid Course course, BindingResult bindingResult){  //BindingResult用于保存错误的信息

        if(bindingResult.hasErrors()){
            log.info(bindingResult.getFieldError().getDefaultMessage());
            return RUtil.error(-2,"出错了"+ bindingResult.getFieldError().getDefaultMessage());
        }


        courseService.update(course);

        return RUtil.success();
    }

    /**
     * 基本分页
     * @param offset
     * @param limit
     * @return
     */
    @RequestMapping(value = "/api/course/list")
    public BTPageDO<CourseExt> list(int offset, int limit){

        int pageIndex=offset/limit;

        if(pageIndex<1){
            pageIndex=1;
        }
        int pageSize=limit;

        BTPageDO<CourseExt> myList=courseService.findByPage(pageIndex,pageSize);



        return  myList;
    }

    @DeleteMapping (value = "/api/course/delete") //valid看Info 是否满足需要
    public R delete(Integer[] ids){  //BindingResult用于保存错误的信息

        for (int i = 0; i < ids.length; i++) {
            //读取data在删除
            //Course item = courseService.findById(ids[i]).get();

            courseService.delete(ids[i]);
        }

        return RUtil.success();
    }
}


